<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>react-demo-25</title>
    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
    <link href="../../../js/font.css" rel="stylesheet" />
  </head>
  <style lang="scss">
    * {
      font-family: "Noto Sans SC", sans-serif;
    }

    body {
      display: flex;
      justify-content: flex-end;
    }

    .title {
      display: inline-flex;
      border: 1px solid blue;
      border-radius: 3px;
    }

    .list {
      width: 300px;
      height: 150px;
      background-color: skyblue;
      overflow: auto;
    }

    .item {
      height: 30px;
    }
  </style>
  <body>
    <!-- 准备容器 -->
    <div id="main"></div>

    <!-- 引入react核心库 -->
    <script
      type="text/javascript"
      src="../../../js/react.development.min.js"
    ></script>
    <!-- 引入react-dom，用于操作dom -->
    <script
      type="text/javascript"
      src="../../../js/react-dom.development.min.js"
    ></script>

    <!-- 引入prop-types -->
    <script src="../../../js/prop-types.js"></script>

    <!-- 引入babel，用于编译jsx -->
    <script src="../../../js/babel.min.js"></script>

    <!-- 此处一定要写babel，用于提示babel对该内容进行编译 -->
    <script type="text/babel">
      class ListDemo extends React.Component {
        state = {
          items: [],
        };
        list = React.createRef();

        componentDidMount() {
          // 每隔一秒钟新增一条新闻
          setInterval(() => {
            const { items } = this.state;
            const item = "Item " + (items.length + 1);
            this.setState({
              items: [item, ...items],
            });
          }, 1000);
        }
        getSnapshotBeforeUpdate() {
          return this.list.current.scrollHeight;
        }
        componentDidUpdate(props, state, snapshot) {
          console.log(state, props, snapshot);
          // linux系统会反常
          this.list.current.scrollTop +=
            this.list.current.scrollHeight - snapshot;
        }
        render() {
          return (
            <div className="list" ref={this.list}>
              {this.state.items.map((value, index) => {
                return (
                  <div className="item" key={value}>
                    {value}
                  </div>
                );
              })}
            </div>
          );
        }
      }
      ReactDOM.render(<ListDemo />, document.getElementById("main"));
    </script>
  </body>
</html>
